package com.zealcomm.ivcscustomer.activity

import android.os.Bundle
import android.os.Vibrator
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.zco.util.ToastUtil
import com.zealcomm.commonui.base.BaseActivity
import com.zealcomm.ivcscustomer.databinding.ActivityScanBinding
import com.zealcomm.utils.inflate

class ScanActivity : BaseActivity(), QRCodeView.Delegate {

    private val binding : ActivityScanBinding by inflate()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.zxingview.setDelegate(this)
    }

    override fun onStart() {
        super.onStart()
        binding.zxingview.startCamera() // 打开后置摄像头开始预览，但是并未开始识别
        binding.zxingview.startSpotAndShowRect() // 显示扫描框，并开始识别
    }

    override fun onStop() {
        binding.zxingview.stopCamera() // 关闭摄像头预览，并且隐藏扫描框
        super.onStop()
    }

    override fun onDestroy() {
        binding.zxingview.onDestroy() // 销毁二维码扫描控件
        super.onDestroy()
    }

    override fun onScanQRCodeSuccess(result: String?) {
        vibrate()
        binding.zxingview.stopCamera()
        if (result == null){
            ToastUtil.showShort("无法识别")
        }else{
            if (result.startsWith("http" , true)){
                finish()
            }else{

            }
        }
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        var tipText: String = binding.zxingview.scanBoxView.tipText
        val ambientBrightnessTip = "\n环境过暗，请打开闪光灯"
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                binding.zxingview.scanBoxView.tipText = tipText + ambientBrightnessTip
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
                binding.zxingview.scanBoxView.tipText = tipText
            }
        }
    }

    override fun onScanQRCodeOpenCameraError() {
        ToastUtil.showShort("打开相机出错")
    }

    private fun vibrate() {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }
}